package com.sg.business.vault.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;
import org.eclipse.core.commands.Command;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPart;

import com.mobnut.db.DBActivator;
import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.sg.business.model.Document;
import com.sg.business.model.DummyModel;
import com.sg.business.model.Folder;
import com.sg.business.model.IModelConstants;
import com.sg.widgets.MessageUtil;
import com.sg.widgets.command.AbstractNavigatorHandler;
import com.sg.widgets.part.editor.DataObjectDialog;
import com.sg.widgets.viewer.ViewerControl;

public class SetSecurityForFolder extends AbstractNavigatorHandler {

	@Override
	protected void execute(PrimaryObject selected, IWorkbenchPart part,
			ViewerControl vc, Command command, Map<String, Object> parameters,
			IStructuredSelection selection) {
		try {
			DummyModel dummyModel = ModelService
					.createModelObject(DummyModel.class);
			DataObjectDialog openDialog = DataObjectDialog.openDialog(
					dummyModel, "setsecurity.folder", true, null);
			if (openDialog.getReturnCode() == DataObjectDialog.OK) {
				String security = dummyModel
						.getStringValue(Document.F_SECURITY);
				if (security == null) {
					return;
				}
				List<ObjectId> _ids = new ArrayList<ObjectId>();
				if (selected instanceof Folder) {
					_ids.addAll(getDocumentId((Folder) selected));

				} else if (selected instanceof Document) {
					_ids.add(selected.get_id());
				}
				if (_ids.size() > 0) {
					doSetSecurity(security, _ids);
				}
			}
		} catch (Exception e) {
			MessageUtil.showToast(e);
		}
	}

	private List<ObjectId> getDocumentId(Folder folder) {
		List<ObjectId> result = new ArrayList<ObjectId>();
		result.addAll(folder.getDocumentIds());
		return result;
	}

	private void doSetSecurity(String security, List<ObjectId> _ids) {
		DBCollection docCol = DBActivator.getCollection(IModelConstants.DB,
				IModelConstants.C_DOCUMENT);
		docCol.update(new BasicDBObject().append(Document.F__ID,
				new BasicDBObject().append("$in", _ids)), new BasicDBObject()
				.append("$set", new BasicDBObject().append(Document.F_SECURITY,
						security)), false, true);

	}
}
